﻿using System.Windows.Forms;
using FirstFloor.ModernUI.Windows.Controls;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Tisbi.LawFirm.BL;
using Tisbi.LawFirm.UI.Views.Controls.Forms;

namespace Tisbi.LawFirm.UI.ViewModel
{
    public class AdminSettingsViewModel : ViewModelBase
    {
        public RelayCommand SettingSqlConnectionStringCommand { get; private set; }
        public RelayCommand BackUpCommand { get; private set; }
        public RelayCommand RestoreCommand { get; private set; }

        public AdminSettingsViewModel()
        {
            SettingSqlConnectionStringCommand = new RelayCommand(SettingSqlConnectionString);
            BackUpCommand = new RelayCommand(BackUpDataBase);
            RestoreCommand = new RelayCommand(RestoreDataBase);
        }

        private void RestoreDataBase()
        {
            var dialog = new OpenFileDialog();
            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                MsSqlBackUpHelper.Restore(dialog.FileName);
            }
        }

        private void BackUpDataBase()
        {
            var dialog = new SaveFileDialog();
            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                MsSqlBackUpHelper.Backup(dialog.FileName);
            }
        }

        private void SettingSqlConnectionString()
        {
            if (!SecurityContextSingleton.GetInstance().IsAdministrator())
            {
                Notifyer.Notify("Не достаточно прав доступа, вы должны быть администратором.");
                return;
            }

            var PopUpDialog = new ModernDialog
            {
                Title = "Настройки подключения к БД",
                Content = new SqlConnectionStringBuilder()
            };

            PopUpDialog.Buttons = new[] { PopUpDialog.OkButton, PopUpDialog.CancelButton };

            PopUpDialog.OkButton.Content = "Сохранить";
            PopUpDialog.CancelButton.Content = "Отмена";
            PopUpDialog.CancelButton.IsCancel = true;

            PopUpDialog.OkButton.Command = new RelayCommand(() =>
            {
                var model = PopUpDialog.DataContext as SqlConnectionStringViewModel;
                if (model == null)
                {
                    Notifyer.NotifyError("Model is null", null);
                    PopUpDialog.Close();
                    return;
                }

                ConfigurationHelper.UpdateConnectionString(model);
            });

            PopUpDialog.ShowDialog();
        }
    }
}
